import React, {useState, useEffect, useRef} from 'react';
import echarts from 'echarts';
import {Spin} from 'antd';
import _ from 'lodash';

import {TARGET_TYPE, TARGET_TYPE_ENUM} from '~/utils/const';
import {dateFormat, parseToWeek} from '../utils';
import {defaultChartsOption} from './data';

const TrendCharts = props => {
    const {data, duration, sortedTargetTypes} = props;
    const generateOption = data => {
        const selectedLegends = {};
        // 折线图默认展示需求
        Array.from(TARGET_TYPE.keys()).forEach(key => {
            if (
                key === sortedTargetTypes[0]
                || key === TARGET_TYPE_ENUM.pageReady
                || key === TARGET_TYPE_ENUM.TTSR
                || key === TARGET_TYPE_ENUM.TTFB
            ) {
                selectedLegends[key] = true;
            }
            else {
                selectedLegends[key] = false;
            }
        });

        const existTargetMap = new Map();
        for (const key of TARGET_TYPE.keys()) {
            if (sortedTargetTypes.includes(key)) {
                existTargetMap.set(key, TARGET_TYPE.get(key));
            }
        }

        const objData = {};
        const pvData = {};
        data.forEach(item => {
            item.datetime = dateFormat(item.datetime, duration);
            if (Object.prototype.hasOwnProperty.call(objData, item.datetime)) {
                objData[item.datetime].set(item.targetType, item.value);
                pvData[item.datetime].set(`${item.targetType}pv`, item.pv);
            }
            else {
                const map = new Map();
                const pvMap = new Map();
                for (const key of existTargetMap.keys()) {
                    if (key === item.targetType) {
                        map.set(key, item.value);
                        pvMap.set(`${key}pv`, item.pv);
                    }
                    else {
                        map.set(key, 0);
                        pvMap.set(`${key}pv`, 0);
                    }
                }
                objData[item.datetime] = map;
                pvData[item.datetime] = pvMap;
            }
        });
        const dataSetList = [];
        Object.keys(objData).forEach((key, index) => {
            dataSetList[index] = [key];
            try {
                dataSetList[index] = dataSetList[index].concat(
                    Array.from(
                        Object.values(objData)[index].values()
                    )
                );
            }
            catch (e) {
                dataSetList[index] = [];
            }
        });
        const seriesList = [];
        for (const value of existTargetMap.keys()) {
            seriesList.push({
                name: value,
                type: 'line',
                smooth: true
            });
        }

        const getToolTip = (indexFlag, item) =>
            `${item.marker}${TARGET_TYPE.get(parseInt(item.seriesName, 10))}: 
            ${item.value[indexFlag + item.seriesIndex]}
            (pv: ${pvData[item.value[0]].get(`${item.seriesName}pv`)})<br />`;

        return {
            tooltip: {
                trigger: 'axis',
                formatter(param) {
                    const indexFlag = 1;
                    const htmlChunk = param.map(item => getToolTip(indexFlag, item));
                    return `${param[0].name} ${parseToWeek(param[0].name)}<br/>${htmlChunk.join('')}`;
                }
            },
            legend: {
                bottom: 40,
                left: 'center',
                selected: selectedLegends,
                formatter: function name(name) {
                    return TARGET_TYPE.get(parseInt(name, 10));
                }
            },
            grid: {
                top: 25,
                left: '10%',
                bottom: '20%'
            },
            dataset: {
                source: dataSetList
            },
            dataZoom: {
                show: true
            },
            xAxis: {
                type: 'category'
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} ms'
                }
            },
            series: seriesList
        };
    };

    // echarts图标绑定到html上
    const [eChartsInstance, setEChartsInstance] = useState(null);
    useEffect(() => {
        const chartsContainer = echarts.init(document.getElementById('trend-charts'));
        setEChartsInstance(chartsContainer);
        if (data) {
            chartsContainer.setOption(generateOption(data), true);
        }
        else {
            chartsContainer.setOption(defaultChartsOption, true);
        }

        window.onresize = _.throttle(() => {
            chartsContainer.resize();
        }, 1000);
    }, []);
    useEffect(() => {
        if (data && eChartsInstance) {
            eChartsInstance.setOption(generateOption(data), true);
        }
    }, [data]);
    return (
        <div className="trend-body">
            <div id="trend-charts">
                charts
            </div>
        </div>
    );
};
export default props => {
    const {data, loading, duration, sortedTargetTypes} = props;
    return (
        <Spin spinning={loading}>
            <TrendCharts data={data} duration={duration} sortedTargetTypes={sortedTargetTypes} />
        </Spin>
    );
};
